from rest_framework import serializers
from goods.models import SKUImage, SKU


class SKUImageModelSerializer(serializers.ModelSerializer):
    sku_id = serializers.IntegerField(label='商品id')
    sku = serializers.StringRelatedField(label='商品')

    class Meta:
        model = SKUImage
        fields = ('id', 'sku', 'sku_id', 'image')

    def validate_sku_id(self, value):
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('商品不存在')
        self.sku = sku
        return value

    def create(self, validated_data):
        instance = super().create(validated_data)
        if not self.sku.default_image:
            self.sku.default_image = instance.image
            self.sku.save()
        return instance

    def update(self, instance, validated_data):
        old_image_url = instance.image.name
        instance = super().update(instance, validated_data)
        if self.sku.default_image.name == old_image_url:
            self.sku.default_image = instance.image
            self.sku.save()
        return instance


class SKUModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id', 'name')
